<?php
namespace Home\Controller;

use Think\Controller;

/**
 * 支付网关通知
 * Class NotifyController
 * @package Home\Controller
 */
class NotifyController extends Controller
{
    protected $needFilter = false;



    public function index()
    {
        die('Dangrous');
    }

    /**
     * 支付宝支付回调
     * http://local.wx.com/notify/alipayreturn?
     * out_trade_no=100015
     * &request_token=requestToken
     * &result=success
     * &trade_no=2016102521001004500267608022
     * &sign=6c42572790b8cbe4f638c1c395b30b3f
     * &sign_type=MD5
     */
    public function alipayreturn()
    {
        // 去掉一些客户端开webview时候增加的参数, 避免验签错误
//        unset(
//            $_GET['mi'],
//            $_GET['ot'],
//            $_GET['cookiekey'],
//            $_GET['key'],
//            $_GET['udid'],
//            $_GET['ua']
//        );

        vendor('AliWapPay.Corefunction');
        vendor('AliWapPay.MD5function');
        vendor('AliWapPay.Notify');
        vendor('AliWapPay.Submit');

        $alipay_config = C('ALIPAY_CONFIG');

        // 计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verified = $alipayNotify->verifyReturn();
        if ($verified) {
            $trade_no = $_GET['out_trade_no']; // 商户订单号

            $payMdl = new \Common\Model\LockorderModel();

            /* @warn 不对同步回调进行处理了, 因为同步回调没有各种价格, 不好! 这样不好!
             * $alipay_trade_no = $_GET['trade_no']; // 支付宝交易号
             * $result = $_GET['result']; // 交易状态
             * $orderAppendParam = array(
             * 'gateway' => 'alipay',
             * 'gateway_notify_time' => date('Y-m-d H:i:s'),
             * );
             * $ret = $payMdl->setPaymentPaid($trade_no, $alipay_trade_no, $orderAppendParam);
             * if ($ret) {
             * // TODO seems like nothing to do
             * }
             */

            $payInfo = $payMdl->getOrderInfo($trade_no);
            if ($payInfo) {

                $redirectUrl = "/order/jumporder?orderid={$payInfo['id']}";

                header('Location: ' . $redirectUrl);

            } else {
                // TODO log
                E('系统错误');
            }
        } else {
            // TODO log
            E('系统错误');
        }
    }

    /**
     * 支付宝退款通知地址
     */
//    public function alipayRefund()
//    {
//        $alipayLogic = new \Home\Logic\AlipayLogic();
//        $alipayLogic->handleNotify();
//    }

    /**
     * 支付宝支付通知
     */
    public function alipay()
    {
        vendor('AliWapPay.Corefunction');
        vendor('AliWapPay.MD5function');
        vendor('AliWapPay.Notify');
        vendor('AliWapPay.Submit');

        $alipay_config = C('ALIPAY_CONFIG');

        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if ($verify_result) {
            $notify_data = $_POST['notify_data'];

            // 解密（如果是RSA签名需要解密，如果是MD5签名则下面一行清注释掉）
            // $notify_data = $alipayNotify->decrypt($_POST['notify_data']);

            $doc = new \DOMDocument();
            $doc->loadXML($notify_data);
            if (!empty($doc->getElementsByTagName("notify")->item(0)->nodeValue)) {
                $trade_no = $doc->getElementsByTagName("out_trade_no")->item(0)->nodeValue;
                $alipay_trade_no = $doc->getElementsByTagName("trade_no")->item(0)->nodeValue;
                $trade_status = $doc->getElementsByTagName("trade_status")->item(0)->nodeValue;

                if (empty($trade_no) or empty($alipay_trade_no) or empty($trade_status)) {
                    log_message("alipay-notify", 'notify处理失败E:' . json_encode($_POST), 'error');
                    echo 'fail';
                    exit();
                }

                // 注意：该种交易状态只在两种情况下出现
                // 1、开通了普通即时到账，买家付款成功后。
                // 2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
                if ($trade_status == 'TRADE_FINISHED') {
                    // 获取买家信息
                    $buyer_email = $doc->getElementsByTagName("buyer_email")->item(0)->nodeValue; // 买家支付宝账号
                    $total_fee = $doc->getElementsByTagName("total_fee")->item(0)->nodeValue; // 总金额
                    $buyer_id = $doc->getElementsByTagName("buyer_id")->item(0)->nodeValue; // 买家支付宝用户号
                    // $notify_time = $doc->getElementsByTagName("notify_time")->item(0)->nodeValue; // 通知时间

                    // 支付成功订单处理
                    $orderAppendParam = array(
                        'buyer_account' => $buyer_email,
                        'buyer_id' => $buyer_id,
                        'gateway' => 'alipay',
                        'gateway_total_fee' => $total_fee,
                        'gateway_notify_time' => date('Y-m-d H:i:s'),
                    );

                    $payLogic = new \Common\Logic\PayLogic();
                    $ret = $payLogic->setPaymentPaid($trade_no, $alipay_trade_no, $orderAppendParam);
                    if ($ret) {
                        echo "success";
                        exit();
                    }
                } //* 注意：该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
                else if ($trade_status == 'TRADE_SUCCESS') {
                    // 获取买家信息
                    $buyer_email = $doc->getElementsByTagName("buyer_email")->item(0)->nodeValue; // 买家支付宝账号
                    $total_fee = $doc->getElementsByTagName("total_fee")->item(0)->nodeValue; // 总金额
                    $buyer_id = $doc->getElementsByTagName("buyer_id")->item(0)->nodeValue; // 买家支付宝用户号
                    // $notify_time = $doc->getElementsByTagName("notify_time")->item(0)->nodeValue; // 通知时间

                    // 支付成功订单处理
                    $orderAppendParam = array(
                        'buyer_account' => $buyer_email,
                        'buyer_id' => $buyer_id,
                        'gateway' => 'alipay',
                        'gateway_total_fee' => $total_fee ,
                        'gateway_notify_time' => date('Y-m-d H:i:s')
                    );

                    $payLogic = new \Common\Logic\PayLogic();
                    $ret = $payLogic->setPaymentPaid($trade_no, $alipay_trade_no, $orderAppendParam);
                    if ($ret) {
                        echo "success";
                        exit();
                    }
                }
                //*/

                log_message('alipay-notify', 'notify处理失败A:' . json_encode($_POST), 'error');
                echo "fail";
                exit();
            } else {
                log_message('alipay-notify', 'notify处理失败B:' . json_encode($_POST), 'error');
                echo "fail";
                exit();
            }
        } else {
            log_message('alipay-notify', 'notify处理失败C' . json_encode($_POST), 'error');
            echo "fail";
            exit();
        }
    }

    /**
     * 微信支付通知
     */
    public function wxpay()
    {
        $postXML = $GLOBALS['HTTP_RAW_POST_DATA'];
        if (!isset($postXML)) {
            log_message("danger:wxpay-notify-nodata", "没有收到微信支付通知的解析数据");
            echo 'fail';
            exit();
        }

        // TODO 先验证签名
        $verified = true;
        if ($verified) {
            // 获取有用的参数
            $doc = new \DOMDocument();
            $doc->loadXML($postXML);

            // 财付通订单号
            $transaction_id = $doc->getElementsByTagName("transaction_id")->item(0)->nodeValue;
            // 商户交易单号
            $payID = $doc->getElementsByTagName("out_trade_no")->item(0)->nodeValue;
            // 商品金额,以分为单位
            $total_fee = $doc->getElementsByTagName("total_fee")->item(0)->nodeValue;
            // 用户标识
            $openId = $doc->getElementsByTagName("openid")->item(0)->nodeValue;
            // 支付结果 SUCCESS/FAIL
            $result_code = $doc->getElementsByTagName("result_code")->item(0)->nodeValue;

            if ('SUCCESS' === $result_code) {
                // 支付成功订单处理
                $orderAppendParam = array(
                    'buyer_id' => $openId,
                    'gateway' => 'wxpay',
                    'gateway_total_fee' => $total_fee,
                    'gateway_notify_time' => date('Y-m-d H:i:s'),
                );

                $payLogic = new \Common\Logic\PayLogic();
                $ret = $payLogic->setPaymentPaid($payID, $transaction_id, $orderAppendParam);
                if ($ret) {
                    echo 'success';
                    exit();
                }
            }
            log_message("error:wxpay-notify", 'notify处理失败pA');
            echo 'fail';
            exit();

        } else {
            log_message("danger:wxpay-notify", 'notify验证签名失败');
            echo 'fail';
            exit();
        }
    }

}